use wasm_bindgen::prelude::*;
use web_sys::{CanvasRenderingContext2d, HtmlCanvasElement};

#[wasm_bindgen]
pub fn draw_mandelbrot(canvas_id: &str, width: u32, height: u32, max_iter: u32) {
    let document = web_sys::window().unwrap().document().unwrap();
    let canvas = document.get_element_by_id(canvas_id).unwrap();
    let canvas: HtmlCanvasElement = canvas.dyn_into().unwrap();
    
    canvas.set_width(width);
    canvas.set_height(height);
    
    let ctx = canvas
        .get_context("2d")
        .unwrap()
        .unwrap()
        .dyn_into::<CanvasRenderingContext2d>()
        .unwrap();
    
    // 高性能分形渲染算法
    for x in 0..width {
        for y in 0..height {
            let mut zx = 0.0;
            let mut zy = 0.0;
            let cx = (x as f64 / width as f64) * 3.5 - 2.5;
            let cy = (y as f64 / height as f64) * 2.0 - 1.0;
            let mut i = 0;

            while zx * zx + zy * zy < 4.0 && i < max_iter {
                let tmp = zx * zx - zy * zy + cx;
                zy = 2.0 * zx * zy + cy;
                zx = tmp;
                i += 1;
            }

            let color = if i == max_iter {
              "#000"
            } else {
                &format!("#{:02x}{:02x}{:02x}", i*8%256, i*6%256, i*4%256)
            };

            ctx.set_fill_style(&JsValue::from_str(color));
            ctx.fill_rect(x as f64, y as f64, 1.0, 1.0);
        }
    }
}

